import { defineStore } from 'pinia'
import { ref } from 'vue'
import { AdminLogin, AdminLogout, getAdminCurrent, updateAdmin, getCaptcha } from '@/api/admin'

export const useAdminStore = defineStore('admin', () => {
    const adminToken = ref(localStorage.getItem('adminToken') || '')
    const adminInfo = ref(JSON.parse(localStorage.getItem('adminInfo') || '{}'))
    const captchaInfo = ref(null)

    // 获取验证码
    const getCaptchaAction = async () => {
        try {
            const response = await getCaptcha()
            if (response.code === 0) {
                captchaInfo.value = response.data
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 管理员登录
    const adminLogin = async (loginData) => {
        try {
            const response = await AdminLogin(loginData)
            if (response.code === 0) {
                adminToken.value = response.data.token
                adminInfo.value = response.data.admin

                // 存储到localStorage
                localStorage.setItem('adminToken', adminToken.value)
                localStorage.setItem('adminInfo', JSON.stringify(adminInfo.value))

                // 登录成功后清除验证码信息
                captchaInfo.value = null

                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }


    // 管理员登出
    const adminLogout = async () => {
        try {
            // 先调用登出接口
            await AdminLogout()
        } catch (error) {
            console.error('登出接口调用失败:', error)
        } finally {
            // 无论如何都清除本地存储
            clearAdminData()
        }
    }

    // 清除管理员数据
    const clearAdminData = () => {
        adminToken.value = ''
        adminInfo.value = {}
        localStorage.removeItem('adminToken')
        localStorage.removeItem('adminInfo')
        console.log('管理员数据已清除')
    }

    // 检查管理员是否登录
    const isAdminLoggedIn = () => {
        return !!adminToken.value
    }

    // 获取管理员ID
    const getAdminId = () => {
        return adminInfo.value.admin_id || adminInfo.value.id
    }

    // 获取管理员名称
    const getAdminName = () => {
        return adminInfo.value.admin_name || adminInfo.value.name || adminInfo.value.email || '管理员'
    }

    // 获取管理员邮箱
    const getAdminEmail = () => {
        return adminInfo.value.email || ''
    }

    // 刷新管理员信息
    const refreshAdminInfo = async () => {
        try {
            const response = await getAdminCurrent()
            if (response.code === 0) {
                adminInfo.value = response.data
                localStorage.setItem('adminInfo', JSON.stringify(adminInfo.value))
                return Promise.resolve(response)
            } else {
                // 如果获取当前管理员信息失败，清除本地存储
                clearAdminData()
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            // 如果请求失败，清除本地存储
            clearAdminData()
            return Promise.reject(error)
        }
    }

    // 更新管理员信息
    const updateAdminAction = async (adminId, data) => {
        try {
            const response = await updateAdmin(adminId, data)
            if (response.code === 0) {
                // 如果更新的是当前管理员的信息，更新本地存储
                if (adminId === getAdminId()) {
                    adminInfo.value = { ...adminInfo.value, ...data }
                    localStorage.setItem('adminInfo', JSON.stringify(adminInfo.value))
                }
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    return {
        adminToken,
        adminInfo,
        adminLogin,
        adminLogout,
        clearAdminData,
        isAdminLoggedIn,
        getAdminId,
        getAdminName,
        getAdminEmail,
        refreshAdminInfo,
        updateAdminAction,
        getCaptchaAction

    }
})